package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Order;
import com.atguigu.service.OrderService;
import com.atguigu.util.SMSUtils;
import com.atguigu.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/Order")
public class OrderController {

    @Reference
    OrderService orderService;

    @Autowired
    JedisPool jedisPool;

    @PostMapping("/verification")
    public Result verification(String telephone){

        try {
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            SMSUtils.sendShortMessage(telephone,code);
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,5*60,code);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @PostMapping("/subscribe")
    public Result subscribe(@RequestBody Map map){

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //判断验证码是否正确，或者有效
        String s = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        if(s == null){
            return new Result(false,"验证码已失效");
        }

        if(!s.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        try {
            return orderService.subscribe(map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"预约失败");
        }

    }

    @RequestMapping("/findById")
    public Result findById(Integer id){

        try {
            Map map = orderService.findById(id);
            return new Result(true,"查询订单信息成功",map);
        }catch (Exception e){
            return new Result(false,"查询订单信息失败");
        }
    }


}
